/**
 * 商户中心接口
 * @author ytl
 */
import Qs from 'qs';
import axios from 'axios';
import {INTERACE_MERCHANT_CENTER_BASE_URL} from 'components/api/index-local';
import {getLocalStorageItem, setLocalStorageItem} from 'components/api/utils';

/**
 * 创建axios实例
 * @return {axios}
 */
export function createHttp() {
  let $httpMerchant = axios.create({
    baseURL: INTERACE_MERCHANT_CENTER_BASE_URL,
    transformRequest: [function (data) {
      data = Qs.stringify(data);
      return data;
    }],
    headers: {'Content-Type': 'application/json;charset=UTF-8'},
    timeout: 5000
  });

// 添加一个响应拦截器
  $httpMerchant.interceptors.response.use(res => {
    return res.data;
  }, err => {
    console.log(err);
    return Promise.reject(err);
  });
  return $httpMerchant;
}
/**
 * 使用门店编码获取单个/部分门店信息
 * @param branchIdArr 门店编号数组
 */
export function getBranchMapByIdes (branchIdArr) {
  let localBranches = getLocalStorageItem('branches') ? getLocalStorageItem('branches') : {};
  let refresh = false;
  if (localBranches) {
    for (let branchId in branchIdArr) {
      if (!localBranches[branchId]) {
        refresh = true;
        break;
      }
    }
    if (refresh === false) {
      return new Promise(localBranches);
    }
  }
  let url = '/branches/' + branchIdArr.join(',');
  let $httpMerchant = createHttp();
  $httpMerchant.interceptors.response.use(res => {
    for (let rowIndex in res) {
      let row = res[rowIndex];
      let branchId = row.id;
      localBranches[branchId] = row;
    }
    setLocalStorageItem('branches', localBranches, 86400);
    return localBranches;
  });

  return $httpMerchant.get(url);
}
/**
 * 自助点餐接口
 * 获取门店列表，带有图片和经纬度
 */
export function getBranchWithDish(params) {
  let mapType = 'GD'; // 地图类型高德
  let url = '/branches/uid/' + params.uid + '/authid/' + params.authId + '/businessType/' + params.businessType + '/mapType/' + mapType;
  let $httpMerchant = createHttp();
  return $httpMerchant.get(url)
}
